<?php

namespace Dls\Entity\V0\Form;

use Dls\Entity\V0\Form;
use Illuminate\Support\Collection;

/**
 * usage：
 * form->panel('基本信息', function (Form $form) {})->panel('xxx', function(Form $form) {});
 *
 * Class Panel
 * @package Dls\Entity\V0\Form
 */
class Panel
{
    /**
     * @var Form
     */
    protected $form;

    /**
     * @var Collection
     */
    protected $panels;

    /**
     * @var int
     */
    protected $offset = 0;

    /**
     * Tab constructor.
     *
     * @param Form $form
     */
    public function __construct(Form $form)
    {
        $this->form = $form;

        $this->panels = new Collection();
    }

    /**
     * Append a tab section.
     *
     * @param string   $title
     * @param \Closure $content
     * @param bool     $active
     *
     * @return $this
     */
    public function append($title, \Closure $content)
    {
        $fields = $this->collectFields($content);

        $id = 'form-'.($this->panels->count() + 1);

        $this->panels->push(compact('id', 'title', 'fields'));

        return $this;
    }

    /**
     * Collect fields under current panel.
     *
     * @param \Closure $content
     *
     * @return Collection
     */
    protected function collectFields(\Closure $content)
    {
        call_user_func($content, $this->form);

        $all = $this->form->builder()->fields();

        $fields = $all->slice($this->offset);

        $this->offset = $all->count();

        return $fields;
    }

    /**
     * Get all panels.
     *
     * @return Collection
     */
    public function getPanels()
    {
        // If there is no active tab, then active the first.
        if ($this->panels->isEmpty()) {
            $first = $this->panels->first();

            $this->panels->offsetSet(0, $first);
        }

        return $this->panels;
    }

    /**
     * @return bool
     */
    public function isEmpty()
    {
        return $this->panels->isEmpty();
    }
}
